from time import sleep
import json
import pandas as pd

from base.base import Base


# 统计物联平台的所有接口

# 登录nacos，获取token
base=Base()
url='http://192.168.146.18:8848/nacos/v1/auth/users/login'
param_type='FROM'
data={
    'username':'nacos',
    'password':'Tw2024@na!'
}
authorization=base.send_post(url,param_type,data=data)
accesstoken=json.loads(authorization)['accessToken']

sleep(1)
# 提取所有的服务名
url='http://192.168.146.18:8848/nacos/v1/ns/catalog/services?hasIpCount=true&withInstances=false&pageNo=1&pageSize=50&serviceNameParam=&groupNameParam=&namespaceId=559d7cb0-8ef1-4393-b28f-41843b0106ae'
headers={
    'Accesstoken':accesstoken
}
res=json.loads(base.send_get(url,headers=headers))

server_list=[]
for i in range(int(res['count'])):
    server_list.append(res['serviceList'][i]['name'])
# print(server_list)

# 提取服务名对应的IP、port
ip_port_list=[]
for server in server_list:
    url='http://192.168.146.18:8848/nacos/v1/ns/catalog/instances?&serviceName='+server+'&clusterName=DEFAULT&groupName=DEFAULT_GROUP&pageSize=10&pageNo=1&namespaceId=559d7cb0-8ef1-4393-b28f-41843b0106ae'
    headers={
        'Accesstoken':accesstoken
    }
    res=json.loads(base.send_get(url,headers=headers))
    ip_port_list.append(str(res['list'][0]['ip'])+':'+str(res['list'][0]['port']))
print(ip_port_list)


# 循环调用swagger接口读取信息，并将信息存入excel
interface_list=[]
count=0
for ip_port in ip_port_list:
    url=f'http://{ip_port}/v2/api-docs'
    try:
        response = base.send_get(url)
        path = json.loads(response)['paths']
        for interface in path.items():
            for methed in interface[1].items():
                if methed[0] in ('post','get'):
                    consumes = methed[1].get('consumes', '')
                    parameters=methed[1].get('parameters', '')
                    responses=methed[1].get('responses', '')

                    # 提取参数，因为小部分不符合规则，先不用
                    # if parameters is not None:
                    #     para={}
                    #     for parameter in parameters:
                    #         if parameter['in']=="query":
                    #             para[parameter['name']]=''
                    #         else:
                    #             schema=parameter['schema']
                    #             if 'originalRef' in schema:
                    #                 name=schema['originalRef']
                    #                 for obj in json.loads(response)['definitions'][name]['properties']:
                    #                     para[obj]=''
                    #             else:
                    #                 para[parameter['name']]=''
                    #     list=[server_list[count],methed[1]['summary'],interface[0],methed[0],consumes,para,parameters,responses]

                    list=[server_list[count],methed[1]['summary'],interface[0],methed[0],consumes,parameters,responses]
                interface_list.append(list)
    except (json.JSONDecodeError, Exception) as e:
        print(f"Error with  {server_list[count]} {ip_port}: {e}")
    finally:
        sleep(0.1)
        count+=1
print(interface_list)

# 指定列头
columns = ['服务', '接口名', '接口地址','请求方式','数据格式','入参说明','响应']

df = pd.DataFrame(interface_list, columns=columns)

# 将 DataFrame 写入 Excel 文件
df.to_excel('interface2.xlsx', index=False)